package com.jy.api.service.impl;

import com.jy.api.dao.AccountBalanceDao;
import com.jy.api.dao.EmployeeDao;
import com.jy.api.domain.AccountBalance;
import com.jy.api.domain.Employee;
import com.jy.api.service.AccountBalanceService;
import com.jy.api.signUpReq.MarsCallReq.UpdateAccountReq;
import com.jy.api.util.ISyncExecutor;
import com.jy.api.util.RedisSyncLocker;
import com.jy.api.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaohua on 2018/11/22.
 */
@Service
public class AccountBalanceServiceImpl implements AccountBalanceService {
    @Autowired
    private AccountBalanceDao accountBalanceDao;
    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private RedisSyncLocker redisSyncLocker;

    @Override
    public AccountBalance findByStoreId(String storeId) {
        return accountBalanceDao.findByStoreId(storeId);


    }

    @Override
    public Map<String, Object> updateAccountBalance(UpdateAccountReq req)  throws Exception {
        return (Map) redisSyncLocker.idLock(req.getUsername(), new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabledIsTrue(req.getStoreId(), req.getUsername());
                AccountBalance accountBalance = accountBalanceDao.findByStoreId(req.getStoreId());
                AccountBalance balance = null;
                Map<String, Object> map = new HashMap<>();
                if (employee == null) {
                    map.put("result", new Result(400, "手机号码"+req.getUsername()+"不存在，请核实后再填写"));
                    return map;
                }
                if (accountBalance == null) {
                    balance = new AccountBalance(req.getStoreId(), req.getUsername(), req.getAccountPayee(), req.getAccountPeople(), req.getCdCard(), req.getName(), req.getBankName());
                    map.put("result", new Result(200, "修改成功"));
                    map.put("data", accountBalanceDao.save(balance));
                    return map;
                } else {
                    accountBalance.setAccountPayee(req.getAccountPayee());
                    accountBalance.setAccountPeople(req.getAccountPeople());
                    accountBalance.setCdCard(req.getCdCard());
                    accountBalance.setUsername(req.getUsername());
                    accountBalance.setName(req.getName());
                    accountBalance.setBankName(req.getBankName());
                    map.put("result", new Result(200, "修改成功"));
                    map.put("data", accountBalanceDao.save(accountBalance));
                    return map;
                }
            }
        });
    }
}
